import json

from django.contrib.auth import authenticate, logout
from django.contrib.auth.models import User
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Count
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from rest_framework_simplejwt.tokens import RefreshToken

from .models import BlogUser
from blogs.views import *
from blogs.models import BlogArticle
from blogs.views import right_sidebar_content

#用户个人中心数据处理
def user_center(request,username):
    #先判断用户是否登录
    if username:
        #查询该作者所有的博文列表
        blog_articles = BlogArticle.objects.filter(username__username=username).order_by('-created_at')
        # 加入分页处理
        # 创建分页器，每页显示10篇文章
        paginator = Paginator(blog_articles, 4)
        #  获取URL中的页码参数，如果没有则默认为第一页
        page = request.GET.get('page')
        try:
            articles = paginator.page(page)
        except PageNotAnInteger:
            # 如果 page 参数不是整数，则返回第一页
            articles = paginator.page(1)
        except EmptyPage:
            # 如果 page 参数超出范围，则返回最后一页
            articles = paginator.page(paginator.num_pages)
        # 右侧边栏数据
        top_authors, top_articles, categories = right_sidebar_content()
        # 组织传递给模板的数据字典对象
        context = {
            'blog_articles': articles,
            'top_authors': top_authors,
            'top_articles': top_articles,
            'categories': categories
        }
        # 将博文数据传递给模板
        return render(request, 'user_center.html', context)

#处理用户注册
@csrf_exempt
def user_register(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        phone = request.POST.get('phone')
        if username and password and phone:
            try:
                user = BlogUser.objects.create_user(username=username, password=password,phone_number=phone)
                return JsonResponse({'message': 'User registered successfully','code':1})
            except Exception as e:
                return JsonResponse({'error': str(e),'code':0}, status=400)
        else:
            return JsonResponse({'error': 'Username and password are required'}, status=400)
    else:
        return JsonResponse({'error': 'Only POST requests are allowed'}, status=405)

#处理用户登录
@csrf_exempt
def user_login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user:
            request.session['username']=username
            refresh = RefreshToken.for_user(request.user)
            access_token = str(refresh.access_token)
            return JsonResponse({'message': 'Login successful','code':1,'token':access_token})
        else:
            return JsonResponse({'error': 'Invalid username or password','code':-1})
    else:
        return JsonResponse({'error': 'Only POST requests are allowed'}, status=405)

# 注销登录
@csrf_exempt
def user_logout(request):
    if request.method == 'POST':
        # 使用 logout() 函数注销用户并清除 session 中的相关信息
        logout(request)
        print("----")
        # 重定向到某个页面，例如回到首页
        return JsonResponse({'message': 'Logout successful','code':1})
